//
//  NearbyStadiumList.m
//  GolfFriend
//
//  Created by Vescky on 14-3-1.
//  Copyright (c) 2014年 vescky.org. All rights reserved.
//

#import "NearbyStadiumList.h"
#import "AppsLocationManager.h"
#import "AppsEngine.h"
#import "CommonUtility.h"
#import "SVProgressHUD.h"
#import <CoreLocation/CoreLocation.h>

#import "MJRefresh.h"
#import "CacheDaoForStadiumsInfo.h"
#import "JSON.h"

//#import "StadiumDetailInfoView.h"
#import "StadiumDetailViewController.h"
#import "NearbyStadiumCell.h"
#import "UserSession.h"

#define Stadium_Cell_Height 150.0

@interface NearbyStadiumList ()<UITableViewDataSource,UITableViewDelegate,MJRefreshBaseViewDelegate> {
    int currentPage;
    NSMutableArray *stadiumList;
    
    //下拉刷新，上拉加载更多
    MJRefreshHeaderView *_header;
    MJRefreshFooterView *_footer;
}

@end

@implementation NearbyStadiumList

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setTitle:@"商家推荐"];
    [super customBackButton];
    [self initView];
    [self initData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - Private
- (void)initView {
    //初始化刷新view
    _header = [MJRefreshHeaderView header];
    _header.scrollView = stadiumScrollView;
    _header.delegate = self;
    
    // 4.3行集成上拉加载更多控件
    _footer = [MJRefreshFooterView footer];
    _footer.scrollView = stadiumScrollView;
    _footer.delegate = self;
}

- (void)initData {
    stadiumList = [[NSMutableArray alloc] init];
    currentPage = 1;
    //先读缓存数据
    NSMutableArray *cacheArr = [[CacheDaoForStadiumsInfo shareCacheDaoForStadiumsInfo] getStadiums:NSMakeRange(0, 20)];
    if (cacheArr && [cacheArr count] > 0) {
        for (int i = 0; i < [cacheArr count]; i++) {
            NSDictionary *dict = [cacheArr objectAtIndex:i];
            if (dict && [dict objectForKey:@"content"]) {
                [stadiumList addObject:[[dict objectForKey:@"content"] JSONValue]];
            }
        }
        [self refreshTableView];
    }
//    [self getDataFromServer];
    [_header beginRefreshing];
}

- (void)getDataFromServer {
    CLLocation *currentLocation = [[AppsLocationManager sharedManager] currentLocation];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
                                 [NSString stringWithFormat:@"%d",currentPage],@"page",
                                 [[UserSession shareUserSession] getUserId],@"userId",
                                 [NSString stringWithFormat:@"%lf",currentLocation.coordinate.latitude],@"latitude",
                                 [NSString stringWithFormat:@"%lf",currentLocation.coordinate.longitude],@"longitude",nil];
    [[AppsEngine shareAppsEngine] submitRequest:@"gfGetNearbyStadium" param:dict onCompletion:^(id jsonResponse) {
        NSMutableArray *sList = [jsonResponse objectForKey:@"list"];
        if (sList && [sList respondsToSelector:@selector(count)]) {
            [stadiumList addObjectsFromArray:sList];
            stadiumList = [self resortArray:stadiumList];
            [self saveCacheData];
            [self refreshTableView];
        }
        [self endRefreshing];
    } onError:^(NSError *error) {
        NSLog(@"获取数据失败");
        [self endRefreshing];
    } method:@"GET"];
}

- (void)refreshTableView {
    CGRect tbRect = tbStadiums.frame;
    tbRect.size.height = [stadiumList count] * Stadium_Cell_Height;
    if (tbRect.size.height < stadiumScrollView.frame.size.height) {
        tbRect.size.height = stadiumScrollView.frame.size.height;
    }
    [tbStadiums setFrame:tbRect];
    [stadiumScrollView setContentSize:CGSizeMake(stadiumScrollView.frame.size.width, tbRect.size.height + 30)];
    [tbStadiums reloadData];
}

- (NSMutableArray*)resortArray:(NSMutableArray*)_arr {
    if (!_arr || [_arr count] < 1) {
        return nil;
    }
    _arr = [self removeSameItemInArray:_arr];
    
    //位置远近
    NSArray *sortedArr = [_arr sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        NSString *locationString1 = [obj1 objectForKey:@"position"];
        NSString *locationString2 = [obj2 objectForKey:@"position"];
        CLLocation *location1 = getGfLocation(locationString1);
        CLLocation *location2 = getGfLocation(locationString2);
        double distan1 = [[AppsLocationManager sharedManager] getDistance:location1];
        double distan2 = [[AppsLocationManager sharedManager] getDistance:location2];
        
        if (distan1 > distan2) {
            return (NSComparisonResult)NSOrderedDescending;
        }
        else {
            return (NSComparisonResult)NSOrderedAscending;
        }
        
        return (NSComparisonResult)NSOrderedSame;
    }];
    
    return [[NSMutableArray alloc] initWithArray:sortedArr];
}

- (NSMutableArray*)removeSameItemInArray:(NSMutableArray*)_arr {
    NSMutableDictionary *rDict = [[NSMutableDictionary alloc] init];
    for (int i = 0; i < [_arr count]; i++) {
        NSDictionary *_dict = [_arr objectAtIndex:i];
        [rDict setObject:_dict forKey:[_dict objectForKey:@"id"]];
    }
    
    NSMutableArray *rArr = [[NSMutableArray alloc] init];
    NSEnumerator *_enum = [rDict keyEnumerator];
    for (NSString *key in _enum) {
        [rArr addObject:[rDict objectForKey:key]];
    }
    return rArr;
}

- (void)saveCacheData {
    NSMutableArray *cArr = [[NSMutableArray alloc] init];
    for (int i = 0; i < [stadiumList count]; i++) {
        NSDictionary *contentDict = [stadiumList objectAtIndex:i];
        if (contentDict && [contentDict count] > 0) {
            NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:[contentDict objectForKey:@"id"],@"recordId",
                                  [contentDict objectForKey:@"status"],@"status",
                                  [contentDict JSONFragment],@"content", nil];
            if (dict) {
                [cArr addObject:dict];
            }
        }
    }
    
    [[CacheDaoForStadiumsInfo shareCacheDaoForStadiumsInfo] saveStadiums:cArr];
}

- (void)endRefreshing {
    [_header endRefreshing];
    [_footer endRefreshing];
}


#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [stadiumList count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"NearbyStadiumCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if(!cell){
        cell = [[[NSBundle mainBundle] loadNibNamed:@"NearbyStadiumCell" owner:self options:nil] objectAtIndex:0];
    }
    
    if([cell respondsToSelector:@selector(setDataInfo:)]){
        [cell performSelector:@selector(setDataInfo:) withObject:[stadiumList objectAtIndex:indexPath.row]];
    }
    if([cell respondsToSelector:@selector(setDelegate:)]){
        [cell performSelector:@selector(setDelegate:) withObject:self];
    }
    
    [cell setTag:indexPath.row];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return Stadium_Cell_Height;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tbStadiums deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row > [stadiumList count]) {
        return;
    }
    NSDictionary *dict = [stadiumList objectAtIndex:indexPath.row];
    StadiumDetailViewController *sDetailVc = [[StadiumDetailViewController alloc] init];
    sDetailVc.detailInfo = [[NSMutableDictionary alloc] initWithDictionary:dict];
    sDetailVc.webappLink = [NSString stringWithFormat:@"http://mingyuanhui.sinaapp.com/index.php/webview/index/qiuchang?id=%@",[dict objectForKey:@"id"]];
    sDetailVc.coverImage = [(NearbyStadiumCell*)[tbStadiums cellForRowAtIndexPath:indexPath] imgvAvatar].image;
    [self.navigationController pushViewController:sDetailVc animated:YES];
}

#pragma mark - 刷新的代理方法---进入下拉刷新\上拉加载更多都有可能调用这个方法
- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    if (refreshView == _header) {
        // 下拉刷新
        
    }
    else {
        //上拉加载更多
        
    }
    
    [self getDataFromServer];
}



@end
